import { useContext, useRef } from 'react'
import type { SearchCreateProps } from '../../ListType'
import './SearchCreateStyle.css'
import context from '../../context/Context'
function SearchCreate (props: SearchCreateProps) {

  // #region 变量声明
  const formRef = useRef<HTMLFormElement>(null) // 表单元素
  const { state, dispatch } = useContext(context)
  // console.log(state, dispatch)
  // #endregion

  // #region 函数
  // 点击查询的处理函数
  function searchHandler () {
    if (!formRef.current) return
    // console.dir(formRef.current[0])
    dispatch({ type: 'searchForm', value: {
      ...state.searchForm,
      username: (formRef.current[0] as HTMLInputElement).value.trim(),
      age: Number((formRef.current[1] as HTMLInputElement).value) || undefined,
      sex: (formRef.current[2] as HTMLSelectElement).value === ''
        ? undefined
        : Number((formRef.current[2] as HTMLSelectElement).value) as 0 | 1,
      email: (formRef.current[3] as HTMLInputElement).value.trim() || undefined
    }})
  }
  // 重置
  function resetHandler () {
    if (!formRef.current) return
    dispatch({ type: 'searchForm', value: {
      page: 1,
      pagesize: 5,
      username: '',
      age: undefined,
      sex: undefined,
      email: undefined
    }})
    formRef.current.reset()
  }
  // #endregion


  return (
    <div className="search_create">
      <span>请输入要查找的内容:</span>
      <form ref={ formRef }>
        <div className="form_item">
          <label htmlFor="username">用户名:</label>
          <input type="text" name='username' id='username' autoComplete='autoComplete' />
        </div>
        <div className="form_item">
          <label htmlFor="age">年龄:</label>
          <input type="number" name='age' id='age' />
        </div>
        <div className="form_item">
          <label htmlFor="sex">性别:</label>
          <select name='sex' id='sex'>
            <option value="">请选择</option>
            <option value={ 1 }>男</option>
            <option value={ 0 }>女</option>
          </select>
        </div>
        <div className="form_item">
          <label htmlFor="email">邮箱:</label>
          <input type="email" name='email' id='email' autoComplete='autoComplete' />
        </div>
      </form>
      <button onClick={ searchHandler }>查询</button>
      <button onClick={ resetHandler }>重置</button>
      <button onClick={ props.show }>添加</button>
    </div>
  )
}

export default SearchCreate
